//
//  INHtmlElementUtil.m
//  chanlin
//
//  Created by Ryan on 14-11-14.
//  Copyright (c) 2014年 chanlin. All rights reserved.
//

#import "INHtmlElementUtil.h"
#import "INHtmlElement.h"
#import "NSObject+sagittarius.h"
#import "AttributeStringEntity.h"

@implementation INHtmlElementUtil

SGR_DEF_SINGLETION(INHtmlElementUtil)

- (instancetype)init{
    self=[super init];
    if(self){
        
        NSInteger b=[[NSUserDefaults standardUserDefaults] integerForKey:@"CLFontLevle"];
        self.level=b==0?2:b;
        [self buidFont];
        self.fromatter=[[NSDateFormatter alloc] init];
        self.fromatter.dateFormat=@"yyyy-MM-dd hh:mm:ss";
    }
    return self;
}

- (void)setLevel:(int)level{
    _level=level;
    [[NSUserDefaults standardUserDefaults] setInteger:level forKey:@"CLFontLevle"];
}

- (void)buidFont{
    switch (self.level) {
        case 1:
            self.textFont=[UIFont systemFontOfSize:15.f];
            self.textBlod=[UIFont boldSystemFontOfSize:15.f];
            self.altFont=[UIFont systemFontOfSize:14.f];
            self.altLineSpace=5.f;
            self.textLineSpace=6.f;
            self.fontDesc=@"小号字体";

            break;
        case 2:
            self.textFont=[UIFont systemFontOfSize:17.f];
            self.textBlod=[UIFont boldSystemFontOfSize:17.f];
            self.altFont=[UIFont systemFontOfSize:16.f];
            self.altLineSpace=7.f;
            self.textLineSpace=8.f;
            self.fontDesc=@"普通字体";
            break;

        case 3:
            self.textFont=[UIFont systemFontOfSize:19.f];
            self.textBlod=[UIFont boldSystemFontOfSize:19.f];
            self.altFont=[UIFont systemFontOfSize:18.f];
            self.altLineSpace=9.f;
            self.textLineSpace=10.f;
            self.fontDesc=@"大号字体";

            break;

        case 4:
            self.textFont=[UIFont systemFontOfSize:21.f];
            self.textBlod=[UIFont boldSystemFontOfSize:21.f];
            self.altFont=[UIFont systemFontOfSize:20.f];
            self.altLineSpace=11.f;
            self.textLineSpace=12.f;
            self.fontDesc=@"特大号字体";

            break;

            
        default:
            break;
    }
}

- (NSString *)timeFormateFrom:(NSTimeInterval )time{
    return [self.fromatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:time]];
}

- (void)parseAttrStrWitnString:(NSString *)str
                     andLabels:(NSString *)labels
                andLastElement:(INHtmlElement *)element
                andSuperLabels:(NSString *)superlabels
                          attr:(NSDictionary *)attrs{
    NSString *style=[attrs sgrGetStringForKey:@"style"];
    NSString *pstyle=[attrs sgrGetStringForKey:@"pStyle"];
    NSString *url=[attrs sgrGetStringForKey:@"href"];
    if (_isStrNULL(str)) {
        return;
    }
    
    AttributeStringEntity *attr=[[AttributeStringEntity alloc] init];
    NSString *label=[labels lowercaseString];
    [element.attributeEntitys addObject:attr];
    if([self isParagraphLabels:label]){
        element.paragraphLabels=label;
        [self _fitoutAttributeString:str
                          andElement:element
                             andFont:self.textFont blod:NO];
    }else if([@"b" isEqualToString:label]||
             [@"strong" isEqualToString:label]){
        attr.boldText=YES;
        [self _fitoutAttributeString:str
                          andElement:element
                             andFont:self.textBlod blod:NO];
        
        if(_isStrNotNull(pstyle)){
            [self _parseSpanWithString:str andStylesList:pstyle andElement:element];
        }
    }else if([@"span" isEqualToString:label]){
        [self _fitoutAttributeString:str
                          andElement:element
                             andFont:self.textFont blod:NO];
        if(_isStrNotNull(pstyle)){
            [self _parseSpanWithString:str andStylesList:pstyle andElement:element];
            
        }
        
        if(_isStrNotNull(superlabels)
           &&([@"b" isEqualToString:[superlabels lowercaseString]]
              || [@"strong" isEqualToString:[superlabels lowercaseString]])){
               
               [self _fitoutAttributeString:str
                                 andElement:element
                                    andFont:self.textBlod blod:YES];
           }
        
        [self _parseSpanWithString:str andStylesList:style andElement:element];

    }else if([@"a" isEqualToString:[labels lowercaseString]]){
     
        [self _fitoutAttributeString:str
                          andElement:element
                             andFont:self.textFont blod:NO];
        
        if(_isStrNotNull(pstyle)){
            [self _parseSpanWithString:str andStylesList:pstyle andElement:element];
            
        }
        if(_isStrNotNull(superlabels)
           && ([@"b" isEqualToString:[superlabels lowercaseString]]
               || [@"strong" isEqualToString:[superlabels lowercaseString]])){
               
               [self _fitoutAttributeString:str
                                 andElement:element
                                    andFont:self.textBlod blod:NO];
           }
        
        [self _parseAWithString:str andStylesList:url andElement:element];
        
    }
    // 普通或者不认识的标签
    else {
               [self _fitoutAttributeString:str
                          andElement:element
                             andFont:self.textFont blod:NO];
    }

    
}

// 解析A标签
- (void)_parseAWithString:(NSString *)str andStylesList:(NSString *)link andElement:(INHtmlElement *)element{
   
    [self _fitoutAAttributeString:str
                       andElement:element
                          andFont:self.textFont blod:NO];
   
    element.linkUrl=link;
    
}

- (void)_fitoutAttributeString:(NSString *)string
                    andElement:(INHtmlElement *)element
                       andFont:(UIFont *)font
                          blod:(BOOL)isBlod{
    AttributeStringEntity *attributeEntity = [element.attributeEntitys lastObject];
    NSRange textRange = NSMakeRange(element.strValue.length, string.length);
    attributeEntity.textRange = textRange;
    attributeEntity.textFont = font;
    attributeEntity.textFontSize = font.pointSize;
    attributeEntity.boldText=isBlod;

}

// 文本颜色
- (void)_fitoutAttributeString:(NSString *)string
                    andElement:(INHtmlElement *)element
                      andColor:(UIColor *)color andIsColorful:(BOOL)isColorful{
    NSRange textRange = NSMakeRange(element.strValue.length, string.length);
    AttributeStringEntity *attributeEntity = [element.attributeEntitys lastObject];
    attributeEntity.textColorful = isColorful;
    attributeEntity.textRange = textRange;
    attributeEntity.textColor = color;
}

// 文本连接
- (void)_fitoutAAttributeString:(NSString *)string
                     andElement:(INHtmlElement *)element
                        andFont:(UIFont *)font
                           blod:(BOOL)isBlod{
    
    AttributeStringEntity *attributeEntity = [element.attributeEntitys lastObject];
    NSRange textRange = NSMakeRange(element.strValue.length, string.length);
    attributeEntity.textRange = textRange;
    attributeEntity.textFont = font;
    attributeEntity.isUnderline = YES;
    attributeEntity.textFontSize = font.pointSize;
    attributeEntity.textColorful = YES;
    attributeEntity.textColor = [UIColor colorWithRed:0 green:0x42/255.0f blue:0x76/255.0f alpha:1.0f];
    attributeEntity.boldText=isBlod;
}

// 解析 “span”样式标签
- (void)_parseSpanWithString:(NSString *)str andStylesList:(NSString *)stylesList andElement:(INHtmlElement *)element{
    NSArray *stylesArr = [stylesList componentsSeparatedByString:@";"];
    __weak typeof(self) me=self;
    [stylesArr enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *styles = obj;
        NSArray *keyValue = [styles componentsSeparatedByString:@":"];
        // 文本颜色
        if ([@"color" isEqualToString:keyValue[0]]) {
            UIColor *color=[me colorFromStyle:keyValue[1]];
            if(!color) return ;
            
            [me _fitoutAttributeString:str
                              andElement:element
                                andColor:color
                           andIsColorful:YES];
            // 文本大小
        }
//        else if ([@"font-size" isEqualToString:keyValue[0]]) {
//            // 去掉 “px” 后缀
//            CGFloat fontSize = [keyValue[1] substringWithRange:NSMakeRange(0, ((NSString *)keyValue[1]).length-2)].floatValue;
//            // px -> pt
//            if (fontSize > 0.0) {
//                fontSize = FONT_SIZE_WITH_PX(fontSize);
//                // pt
//            }else{
//                fontSize = [self _fontSizeWithStr:keyValue[1]];
//            }
//            [self _fitoutAttributeString:str
//                              andElement:element andFont:[UIFont systemFontOfSize:fontSize]];
//        }
        else if(keyValue.count > 1){
            //NSLog(@"%s -- \"暂不支持：‘%@’样式属性\" - attribute：%@",__FUNCTION__,keyValue[0],keyValue[1]);
        }
    }];
}

- (UIColor *)colorFromStyle:(NSString *)cstyle{
    if(_isStrNULL(cstyle)) return nil;
    NSArray *colors=[cstyle componentsSeparatedByString:@","];
    if([colors count]<3) return nil;
    NSString *str=[colors sgrGetStringForIndex:0];
    if(str.length<5) return nil;
    int r=[[str substringFromIndex:[str rangeOfString:@"rgb("].location+4] intValue];
    str=[colors sgrGetStringForIndex:1];
    int g=[str intValue];
    str=[colors sgrGetStringForIndex:2];
    int b=[[str substringToIndex:[str rangeOfString:@")"].location] intValue];
    return RGB(r, g, b);

}

// 是否为段落标签 YES：是；NO：不是
- (BOOL)isParagraphLabels:(NSString *)labelsName{
    
    if ([@"p" isEqualToString:labelsName]) {
        return YES;
    }else
        if ([@"br" isEqualToString:labelsName]) {
        return YES;
    }else
        if ([@"h1" isEqualToString:labelsName]) {
        return YES;
    }else if ([@"h2" isEqualToString:labelsName]) {
        return YES;
    }else if ([@"h3" isEqualToString:labelsName]) {
        return YES;
    }else if ([@"h4" isEqualToString:labelsName]) {
        return YES;
    }else if ([@"h5" isEqualToString:labelsName]) {
        return YES;
    }else if ([@"h6" isEqualToString:labelsName]) {
        return YES;
    }else if ([@"h7" isEqualToString:labelsName]) {
        return YES;
        // 文章中间没有“p”包裹的白文本
    }else if ([@"body" isEqualToString:labelsName]) {
        return YES;
    }
    return NO;
}

@end
